<template>
  <div class="container mt-4">
    <!-- 页面标题 -->
    <div class="header">
      <h2>单元管理</h2>
      <p class="description">在这里查看、添加、编辑或删除单元信息。</p>
    </div>

    <!-- 搜索和添加按钮 -->
    <div class="top-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入单元号或建筑物名称进行搜索"
        clearable
        prefix-icon="el-icon-search"
        class="search-input"
        @input="handleSearch"
      />
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon> 添加单元
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-responsive">
      <el-table
        :data="paginatedData"
        :key="tableKey"
        border
        class="table table-bordered table-striped"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="unit_number" label="单元号" sortable></el-table-column>
        <el-table-column
          prop="building_name"
          label="建筑物名称"
          sortable
        ></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="filteredData.length > 0"
      background
      layout="prev, pager, next, jumper"
      :total="filteredData.length"
      :page-size="pageSize"
      :current-page.sync="currentPage"
      @current-change="handlePageChange"
      class="pagination"
    />
    
    <!-- 编辑模态框 -->
    <el-dialog v-model="editDialogVisible" title="编辑单元信息" width="500px">
      <el-form :model="currentEdit" label-width="100px" :rules="editRules" ref="editForm">
        <el-form-item label="单元号" prop="unit_number">
          <el-input v-model="currentEdit.unit_number" />
        </el-form-item>
        <el-form-item label="建筑物名称" prop="building_id">
          <el-select v-model="currentEdit.building_id" placeholder="请选择建筑物">
            <el-option
              v-for="building in buildings"
              :key="building.id"
              :label="building.name"
              :value="building.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加模态框 -->
    <el-dialog v-model="addDialogVisible" title="添加单元" width="500px">
      <el-form :model="newUnit" label-width="100px" :rules="addRules" ref="addForm">
        <el-form-item label="单元号" prop="unit_number">
          <el-input v-model="newUnit.unit_number" />
        </el-form-item>
        <el-form-item label="建筑物名称" prop="building_id">
          <el-select v-model="newUnit.building_id" placeholder="请选择建筑物">
            <el-option
              v-for="building in buildings"
              :key="building.id"
              :label="building.name"
              :value="building.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="addUnit">添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ref, computed, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus'; 

export default {
  components: {
    Plus,
  },
  setup() {
    const token = ref(localStorage.getItem("token"));
    const units = ref([]);
    const buildings = ref([]);
    const tableKey = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const searchQuery = ref("");
    const editDialogVisible = ref(false);
    const addDialogVisible = ref(false);
    const currentEdit = ref({});
    const newUnit = ref({
      unit_number: "",
      building_id: null,
    });
    const loading = ref(false);

    // 定义表单引用
    const editForm = ref(null);
    const addForm = ref(null);

    const editRules = {
      unit_number: [
        { required: true, message: "单元号不能为空", trigger: "blur" },
      ],
      building_id: [
        { required: true, message: "请选择建筑物", trigger: "change" },
      ],
    };

    const addRules = {
      unit_number: [
        { required: true, message: "单元号不能为空", trigger: "blur" },
      ],
      building_id: [
        { required: true, message: "请选择建筑物", trigger: "change" },
      ],
    };

    const fetchData = async () => {
      if (token.value) {
        loading.value = true;
        try {
          // 获取建筑物数据
          const buildingsResponse = await axios.get("http://localhost:3008/buildings", {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          });
          buildings.value = buildingsResponse.data.data || [];

          // 获取单元数据并映射建筑物名称
          const unitsResponse = await axios.get("http://localhost:3008/units", {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          });
          const unitsData = unitsResponse.data.data || [];
          units.value = unitsData.map((unit) => {
            const building = buildings.value.find((b) => b.id === unit.building_id);
            return {
              ...unit,
              building_name: building ? building.name : "未知",
            };
          });

          tableKey.value++; // 强制刷新表格
        } catch (error) {
          console.error("服务器连接失败:", error);
          showMessage("服务器连接失败，请稍后再试。", "error");
          units.value = []; // 出错时清空数据
        } finally {
          loading.value = false;
        }
      } else {
        console.error("没有 token 或 token 已过期");
        showMessage("未登录或登录已过期，请重新登录。", "error");
        units.value = []; // 没有token时清空数据
      }
    };

    const showMessage = (text, type = "success") => {
      ElMessage({
        message: text,
        type: type,
        duration: 3000,
      });
    };

    // 搜索过滤
    const filteredData = computed(() => {
      const lowerQuery = searchQuery.value.toLowerCase();
      return units.value.filter(
        (item) =>
          item.unit_number.toLowerCase().includes(lowerQuery) ||
          item.building_name.toLowerCase().includes(lowerQuery)
      );
    });

    // 分页数据
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredData.value.slice(start, end);
    });

    // 页码更改
    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    // 搜索输入处理
    const handleSearch = () => {
      currentPage.value = 1; // 重置到第一页
    };

    // 打开编辑模态框
    const handleEdit = (row) => {
      currentEdit.value = { ...row };
      editDialogVisible.value = true;
    };

    // 关闭编辑模态框
    const closeEditDialog = () => {
      editDialogVisible.value = false;
      currentEdit.value = {};
    };

    // 保存编辑后的单元数据
    const saveEdit = async () => {
      try {
        // 表单验证
        await editForm.value.validate();

        const response = await axios.put(
          `http://localhost:3008/units/${currentEdit.value.id}`,
          {
            unit_number: currentEdit.value.unit_number,
            building_id: currentEdit.value.building_id,
          },
          {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          }
        );
        if (response.status === 200) {
          showMessage("单元信息更新成功", "success");
          // 更新本地数据
          const index = units.value.findIndex((item) => item.id === currentEdit.value.id);
          if (index !== -1) {
            const building = buildings.value.find((b) => b.id === currentEdit.value.building_id);
            units.value[index] = {
              ...currentEdit.value,
              building_name: building ? building.name : "未知",
            };
            tableKey.value++; // 强制刷新表格
          }
          closeEditDialog();
        }
      } catch (error) {
        console.error("编辑失败:", error);
        if (error.response && error.response.data) {
          showMessage(`编辑失败: ${error.response.data.message}`, "error");
        } else if (error.name === 'ValidationError') {
          // 表单验证错误
          showMessage(`编辑失败: 请检查输入内容。`, "error");
        } else {
          showMessage(`编辑失败: ${error.message || "请稍后再试"}`, "error");
        }
      }
    };

    // 打开添加模态框
    const openAddDialog = () => {
      addDialogVisible.value = true;
    };

    // 关闭添加模态框
    const closeAddDialog = () => {
      addDialogVisible.value = false;
      newUnit.value = {
        unit_number: "",
        building_id: null,
      };
    };

    // 添加新单元
    const addUnit = async () => {
      try {
        // 表单验证
        await addForm.value.validate();

        const response = await axios.post(
          "http://localhost:3008/units",
          {
            unit_number: newUnit.value.unit_number,
            building_id: newUnit.value.building_id,
          },
          {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          }
        );
        if (response.status === 201) {
          showMessage("单元添加成功", "success");
          // 重新获取数据
          await fetchData(); 
          closeAddDialog(); 
        }
      } catch (error) {
        console.error("添加失败:", error);
        if (error.response && error.response.data) {
          showMessage(`添加失败: ${error.response.data.message}`, "error");
        } else if (error.name === 'ValidationError') {
          // 表单验证错误
          showMessage(`添加失败: 请检查输入内容。`, "error");
        } else {
          showMessage(`添加失败: ${error.message || "请稍后再试"}`, "error");
        }
      }
    };

    // 删除单元
    const handleDelete = async (row) => {
      if (!row || !row.id) {
        showMessage("未找到有效的单元ID，无法删除。", "error");
        return;
      }

      if (confirm(`确定删除单元号 ${row.unit_number} 吗？`)) {
        try {
          const response = await axios.delete(
            `http://localhost:3008/units/${row.id}`,
            {
              headers: {
                Authorization: `Bearer ${token.value}`,
              },
            }
          );
          showMessage(response.data.message || "删除成功", "success");
          units.value = units.value.filter((unit) => unit.id !== row.id);
          tableKey.value++; // 强制刷新表格
        } catch (error) {
          console.error("删除失败:", error);
          if (error.response && error.response.data) {
            showMessage(`删除失败: ${error.response.data.message}`, "error");
          } else {
            showMessage(`删除失败: ${error.message || "请稍后再试"}`, "error");
          }
        }
      }
    };

    // 页面加载时获取数据
    onMounted(fetchData);

    return {
      units,
      buildings,
      tableKey,
      currentPage,
      pageSize,
      searchQuery,
      paginatedData,
      filteredData,
      handlePageChange,
      handleEdit,
      saveEdit,
      handleDelete,
      editDialogVisible,
      currentEdit,
      addDialogVisible,
      openAddDialog,
      closeEditDialog,
      closeAddDialog,
      addUnit,
      newUnit,
      loading,
      editRules,
      addRules,
      editForm, 
      addForm,  
      handleSearch,
    };
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 28px;
  color: #409EFF;
  margin-bottom: 8px;
}

.header .description {
  font-size: 16px;
  color: #606266;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  max-width: 400px;
  width: 100%;
}

.table-responsive {
  overflow-x: auto;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-button .el-icon {
  margin-right: 5px;
}

@media (max-width: 767px) {
  .top-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .search-input {
    max-width: 100%;
  }

  .el-pagination {
    flex-direction: column;
    align-items: center;
  }
}
</style>
